package main

import (
	"flag"
	"fmt"
	"github.com/6z7/dtomap"
	"io/ioutil"
	"os"
	"path/filepath"
)

var (
	sourcePath string
	destPath   string

	printMapToConsole   bool
	printClassToConsole bool
)

func main() {
	flag.StringVar(&sourcePath, "sp", "", "源文件路径")
	flag.StringVar(&destPath, "dp", "", "输出路径")
	flag.BoolVar(&printMapToConsole, "pmtc", true, "打印转换代码到控制台")
	flag.BoolVar(&printClassToConsole, "pctc", false, "打印解析后的类到控制台")
	flag.Parse()

	if len(sourcePath) == 0 {
		flag.Usage()
		return
	}

	if len(destPath) == 0 {
		destPath = filepath.Dir(sourcePath) + string(filepath.Separator) + "tmp.cs"
	}

	st := dtomap.SourceText{}
	err := st.LoadLines(sourcePath)
	if err != nil {
		panic(err)
	}

	destClass := dtomap.DestClass{}
	dtoParse := &dtomap.DtoParse{}
	for st.NextLine() {
		className := dtoParse.GetClassName(st.Line())
		if len(className) > 0 {
			destClass.Name = className
			continue
		}

		fieldType, fieldName := dtoParse.GetFiled(st.Line())
		if len(fieldType) > 0 {
			field := dtomap.DestField{
				Name: fieldName,
				Type: fieldType,
			}
			destClass.Fields = append(destClass.Fields, field)
		}
	}

	if printClassToConsole {
		fmt.Println(destClass.String())
	}

	newClassString := destClass.NewClassString()
	if printMapToConsole {
		fmt.Println(newClassString)
	} else {
		err := ioutil.WriteFile(destPath, []byte(newClassString), os.ModeType)
		if err != nil {
			panic(err)
		}
	}

}
